<template>
  <div class="login-container">
    <!-- el-form组件：elementUI插件里面的一个组件，经常展示表单元素  model：用于收集表单数据  rules：表单验证规则-->
    <canvas ref="canvas" id="view"></canvas>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h1 class="title">机器人创新实验室</h1>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="账号"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 430px; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
        >登录</el-button
      >
    </el-form>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import {getUserNamePass} from '@/utils/auth.js'
export default {
  name: "Login",
  data() {
    //先不用在意：这里面在进行表单验证，验证用户名与密码操作
    //回首在看这里
    return {
      loginForm: {
        username: getUserNamePass()&&getUserNamePass().username || '',
        password: getUserNamePass()&&getUserNamePass().password || '',
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur',  message:'账号不能为空'}],
        password: [{ required: true, trigger: 'blur', max:20,min:6,message:'密码不小于6位不大于20位' }]
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      timer: null,
      canvas: null,
      mouse: {
        x: -500,
        y: -500,
      },
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },

  mounted() {
    window.addEventListener("resize", this.resize);
    this.canvas = this.$refs.canvas;
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    const that = this;
    const ctx = this.canvas.getContext("2d");

    const pointList = [];
    document.addEventListener("mousemove", this.mousemove);
    class Point {
      constructor() {
        this.x = 0;
        this.y = 0;
        this.goX = 0;
        this.goY = 0;
        this.age = 0;
        this.init();
      }
      init() {
        this.x = Math.random() * that.canvas.width;
        this.y = Math.random() * that.canvas.height;
        this.goX = Math.random() - 0.5;
        this.goY = Math.random() - 0.5;
        this.age = Math.random() * 50;
      }
      update() {
        this.age--;
        if (
          this.x < 0 ||
          this.x > that.canvas.width ||
          this.y < 0 ||
          this.y > that.canvas.height
        ) {
          this.init();
        } else {
          if (this.age < 0) {
            this.goX += (Math.random() - 0.5) * 0.01;
            this.goY += (Math.random() - 0.5) * 0.01;
          }
          this.x += this.goX;
          this.y += this.goY;
        }
        let r = Math.sqrt((that.mouse.x - this.x) ** 2 + (that.mouse.y - this.y) ** 2);
        if (r < 200) {
          this.x += (that.mouse.x - this.x) / 300;
          this.y += (that.mouse.y - this.y) / 300;
        }
      }
      draw() {
        ctx.beginPath();
        ctx.fillStyle = "white";
        ctx.arc(this.x, this.y, 1, 0, Math.PI * 2, true);
        ctx.fill();
      }
    }
    const init = () => {
      for (let i = 0; i < 100; i++) {
        let e = new Point();
        pointList.push(e);
      }
    };
    init();
    const update = () => {
      ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      for (let i = 0; i < pointList.length; i++) {
        pointList[i].update();
        pointList[i].draw();
        for (let j = i; j < pointList.length; j++) {
          let r = Math.sqrt(
            (pointList[i].x - pointList[j].x) ** 2 +
              (pointList[i].y - pointList[j].y) ** 2
          );
          if (r < 100) {
            ctx.beginPath();
            ctx.moveTo(pointList[i].x, pointList[i].y);
            ctx.lineTo(pointList[j].x, pointList[j].y);
            ctx.strokeStyle = "rgba(255,255,255," + (1 - r / 100) + ")";
            ctx.stroke();
          }
        }
      }
    };
    this.timer = setInterval(update, 1000 / 60);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    window.removeEventListener("resize", this.resize);
    document.removeEventListener('mousemove' ,this.mousemove)
  },
  methods: {
    mousemove(evt) {
      this.mouse.x = evt.x;
      this.mouse.y = evt.y;
    },
    resize() {
      this.canvas.width = window.innerWidth;
      this.canvas.height = window.innerHeight;
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    //登录业务：发请求，带着用户名与密码给服务器（成功与失败）
    handleLogin() {
      //这里是在验证表单元素（用户名与密码）的是否符合规则
      this.$refs.loginForm.validate((valid) => {
        //如果符合验证规则
        if (valid) {
          //按钮会有一个loading效果
          this.loading = true;
          //派发一个action:user/login,带着用户名与密码的载荷
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              //登录成功进行路由的跳转
              this.$router.push({ path: this.redirect || "/" });
              //loading效果结束
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          this.$message.error('请填写完整')
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 400px;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: linear-gradient(
    113.58893008880955deg,
    rgb(33, 59, 77) 4.927083333333334%,
    rgb(31, 45, 56) 97.84374999999999%
  );
  position: relative;

  .login-form {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    top: -5%;
    left: 0px;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 30px;
      letter-spacing: 10px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
